<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.sdry.model.zc.ZcSysUserEntity" %>
<% 
	ZcSysUserEntity zcSysUserEntity =  (ZcSysUserEntity)request.getSession().getAttribute("user");
	//String roleId = zcSysUserEntity.getRoleId(); 
	//String roleIds[] = roleId.split(",");
	String roleName = zcSysUserEntity.getRoleName(); 
	String roleNames[] = roleName.split(",");
	boolean isAdmin= false;
	/* for(int i =0;i<roleIds.length;i++){
		if("2".equals(roleIds[i])){
			isAdmin = true;
		}
	} */
	for(int i =0;i<roleNames.length;i++){
		if("管理员".equals(roleNames[i])|| "超级管理员".equals(roleNames[i])){
			isAdmin = true;
		}
	}
%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>库存管理</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
	<link rel="stylesheet" media="all" href="${pageContext.request.contextPath }/assets/formSelects/formSelects-v4.css">
	<link rel="stylesheet" media="all" href="${pageContext.request.contextPath }/assets/formSelects/formSelects-v4.js">
	<style type="text/css">
		.layui-table-view .layui-table-body tr.table_tr_click {
	      background-color: pink;
	    }
	</style>
</head>
<body class="layui-anim layui-anim-up">
	<div class="x-nav">
		<span class="layui-breadcrumb">
  			<a href="">首页</a>
			<a>
				<cite>库存管理</cite>
			</a>
		</span>
    </div>
	<div class="x-body">
		<div class="layui-row">
			<div class="layui-form">
				<div class="layui-input-inline">
					<div class="layui-input-inline" style="width: 285px">
						<select style="width: 285px" class="" name="keyword" id="keyword" lay-filter="keyword">
							<option value="">--请选择供应商--</option>
							<c:forEach items="${allCustomerList }" var="customer">
								<option value="${customer.id}">${customer.customer_name }</option>
							</c:forEach>
						</select>
					</div>
				</div>
				<!-- <div class="layui-input-inline">
					<input style="width:200px" class="layui-input" id="keyword" name="keyword" placeholder="请输入物料产品码或简码"/>
				</div> -->
				<button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
			</div>
		</div>
		<c:choose>  
			<c:when test="<%= isAdmin %>">  
				<script type="text/html" id="toolbarDemo">
					<div class="layui-btn-container">
						<button class="layui-btn layui-btn-normal" lay-event="move"><i class="layui-icon"></i>移库</button>
						<button class="layui-btn layui-btn-normal layui-hide" lay-event="adjust"><i class="layui-icon"></i>库存调整</button>
					</div>
				</script>
			</c:when>  
         
			<c:otherwise>
				<script type="text/html" id="toolbarDemo">
					<div class="layui-btn-container">
						<button class="layui-btn layui-btn-normal" lay-event="move"><i class="layui-icon"></i>移库</button>
					</div>
				</script>
			</c:otherwise>  
		</c:choose>
		
		<div id = "fDiv">
			<table class="layui-hide" id="inventoryInfoList" lay-filter="inventoryInfoList"></table>
		</div>
		<div id = "details">
			<table class="layui-hide" id="inventoryInfoListDetails" lay-filter="inventoryInfoListDetails"></table>
		</div>
		<div id="formDiv" hidden>
			<div class="box">
			    <form class="layui-form layui-card-body" id="addform2">
					<input hidden id="customer_id" name="customer_id">
					<input hidden id="id2" name="id">
					<div class="layui-form-item">
						<div class="layui-inline">
							<label class="layui-form-label">原仓库</label>
							<div class="layui-input-inline" style="width: 150px">
								<input class="layui-input" id="srcWare" readonly="readonly" style="width: 150px">
							</div>
							<div class="layui-input-inline" style="width: 150px">
								<input class="layui-hide" id="src_region_id" name="src_region_id"/>
								<input class="layui-input" id="srcRegion" readonly="readonly" style="width: 150px">
							</div>
						</div>
					</div>
					<div class="layui-form-item">
						<div class="layui-inline">
							<label class="layui-form-label">目标仓库</label>
							<div class="layui-input-inline" style="width: 150px">
								<select style="width: 150px" name="warehouseId" id="warehouseId" lay-filter="warehouseId">
									<option value="">--请选择仓库--</option>
									<c:forEach items="${allWarehouseList }" var="ware">
										<option value="${ware.id }">${ware.warehouse_name }</option>
									</c:forEach>
								</select>
							</div>
							<div class="layui-input-inline" style="width: 150px">
								<select style="width: 150px" name="region_id" id="region_id" lay-filter="region_id">
									<option value="">--请选择库区--</option>
								</select>
							</div>
						</div>
					</div>
					<div class="layui-form-item">
						<div class="layui-input-block">
							<button class="layui-btn  layui-btn-blue" lay-submit lay-filter="addform2" id="subform2">确定</button>
							<button class="layui-btn layui-btn-primary" style="margin-left:120px">取消</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<div id="adjustDiv" hidden>
			<form class="layui-form layui-card-body" id="adjustform">
				<input class="layui-hide" id="inventId" name="inventId">
				<div class="layui-form-item">
					<label class="layui-form-label">库存数量：</label>
					<div class="layui-input-inline" style="width: 250px">
						<input class="layui-input" id="newMnum" name="mNum" type="number"/>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn layui-btn-blue" id="subadjustform" lay-submit lay-filter="adjustform">提交</button>
						<button type="reset" id="adjustReset" class="layui-btn layui-btn-primary" style="margin-left:100px">重置</button>
					</div>
				</div>
			</form>
		</div>
	</div>
	<script type="text/javascript">
		//全局定义一次, 加载formSelects
		layui.config({
		    base: '${pageContext.request.contextPath }/assets/formSelects/' //此处路径请自行处理, 可以使用绝对路径
		}).extend({
		    formSelects: 'formSelects-v4'
		});
		//日期格式转换
		function date2String(timestamp){
			var d = new Date(timestamp);
			var date = (d.getFullYear()) + "-" + 
		       (d.getMonth() + 1<10?"0"+(d.getMonth() + 1):d.getMonth() + 1) + "-" +
		       (d.getDate()<10?"0"+d.getDate():d.getDate());
		       return date;
		}
		layui.use(['table','layer','upload','form','laydate','formSelects'], function(){
			var table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			var formSelects = layui.formSelects;
			
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword = $("#keyword").val();
					//keyword = "'"+keyword+"'";
					var strWhere = "";
					if(keyword!=""){
						strWhere = 'm.customer_id = '+keyword+' and ';
					}
					table.reload('contenttable',{
						method:'get',
						where:{"strWhere":strWhere}
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			table.render({
				elem: '#inventoryInfoList'
				,url:'${pageContext.request.contextPath }/inventoryManagement/selectInventoryInfoList.do'
				,title: '库存列表'
				,id :'contenttable'
				,toolbar: '#toolbarDemo'
				,limits:[10,20,30]
				,cols: [[
					{type: 'checkbox', fixed: 'left'}
					,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
					,{field:'customer', title:'供应商',width:'90',templet:function(row){
						if(row.materiel.customer!=null){
							return row.materiel.customer.customer_name;
						}else{
							return "";
						}
					}}
					,{field:'materiel_name', title:'物料名称',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.materiel_name;
						}else{
							return "";
						}
					}}
					,{field:'materiel_num', title:'未拆产品码',width:'120',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.materiel_num;
						}else{
							return "";
						}
					}}
					,{field:'devanning_code', title:'已拆产品码',width:'120',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.devanning_code;
						}else{
							return "";
						}
					}}
					,{field:'brevity_num', title:'简码',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.brevity_num;
						}else{
							return "";
						}
					}}
					,{field:'packing_quantity', title:'未拆包装数',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.packing_quantity;
						}else{
							return "";
						}
					}}
					,{field:'devanning_num', title:'已拆包装数',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.devanning_num;
						}else{
							return "";
						}
					}}
					,{field:'materiel_size', title:'物料规格',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.materiel_size;
						}else{
							return "";
						}
					}}
					,{field:'materiel_properties', title:'物料型号',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.materiel_properties;
						}else{
							return "";
						}
					}}
					,{field:'mBatch', title:'批次',width:'120', align: 'center'}
					,{field:'mNum', title:'数量',width:'80'}
					,{field:'bigNum', title:'未拆数量',width:'90'}
					,{field:'smallNum', title:'已拆数量',width:'90'}
					,{field:'countAll', title:'总库存',width:'90'}
					,{field:'upper_value', title:'库存上限',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.upper_value;
						}else{
							return "";
						}
					}}
					,{field:'lower_value', title:'库存下限',width:'90',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.lower_value;
						}else{
							return "";
						}
					}}
					,{field:'unit', title:'单位',width:'80',templet:function(row){
						if(row.materiel!=null){
							return row.materiel.unit;
						}else{
							return "";
						}
					}}
					,{field:'region', title:'所属库区',width:'180',templet:function(row){
						if(row.materiel.region!=null){
							return row.materiel.region.region_name;
						}else{
							return "";
						}
					}}
					,{field:'enterDate',width:'120', title:'入库日期'}
					,{field:'userName',width:'120', title:'入库人',templet:function(row){
						if(row.zcSysUser!=null){
							return row.zcSysUser.userName;
						}else{
							return "";
						}
					}}
				]]
				,page: true
				,done:function(res, curr, count){
	                merge(res);
					$('th').css({
	                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
	                })
				}
			});
			//监听行单击事件
			table.on('row(inventoryInfoList)', function(obj){
				var mid = obj.data.mid;
				var mBatch = obj.data.mBatch;
				if(mBatch == ""){
					var strWhere = " mt.mid = "+mid +" and"
				}else{
					var strWhere = " mt.mid = "+mid +" and mt.mBatch = "+mBatch+" and "
				}
				table.render({
					elem: '#inventoryInfoListDetails'
					,url:'${pageContext.request.contextPath }/inventoryManagement/selectInventoryInfoListDetails.do?strWhere='+strWhere
					,title: '库存详情列表'
					,limits:[10,20,30]
					,cols: [[
						{type: 'checkbox', fixed: 'left'}
						,{field:'', title:'序号', sort: true, type:'numbers', width: 60}
						,{field:'location_code', title:'库位条码',templet:function(row){
							if(row.zcTrayAndLocation!=null){
								return row.zcTrayAndLocation.location_code;
							}else{
								return "";
							}
						}}
						,{field:'tray_code', title:'托盘条码'}
						,{field:'materiel_code', title:'物料条码'}
						,{field:'packType', title:'包装类型',templet:function(row){
							if(row.packType==0){
								return "大箱";
							}else{
								return "小箱";
							}
						}}
						,{field:'mNum', title:'物料数量'}
						,{field:'binding_date', title:'绑定日期'}
						,{field:'userName', title:'绑定人',templet:function(row){
							if(row.zcSysUser!=null){
								return row.zcSysUser.userName;
							}else{
								return "";
							}
						}}
						]]
					,page: true
					,done:function(res, curr, count){
		                mergeDetails(res);
						$('th').css({
		                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
		                })
					}
				})
			});
			//监听复选框事件
			table.on('checkbox(inventoryInfoList)',function(obj){
				if(obj.checked == true && obj.type == 'all'){ 
					//点击全选 
					$('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click'); 
				}else if(obj.checked == false && obj.type == 'all'){ 
					//点击全不选 
					$('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click'); 
				}else if(obj.checked == true && obj.type == 'one'){ 
					//点击单行
					if(obj.checked == true){ 
						obj.tr.addClass('layui-table-click'); 
					}else{ 
						obj.tr.removeClass('layui-table-click'); 
					} 
				}else if(obj.checked == false && obj.type == 'one'){ 
					//点击全选之后点击单行 
					if(obj.tr.hasClass('layui-table-click')){
						obj.tr.removeClass('layui-table-click'); 
					} 
				}
			})
			//头事件
			table.on('toolbar(inventoryInfoList)', function(obj){
				var checkStatus = table.checkStatus(obj.config.id);
				var area = $("#area").val();
				var location = $("#location").val();
				var tray = $("#tray").val();
				var data = checkStatus.data;
				switch(obj.event){
		    		case 'move':
		    			if(data.length!=1){
			        		toastr.warning("请选择一条记录！");
			        	}else{
			        		$("#warehouseId").val("");
			        		$("#region_id").val("");
			        		form.render('select');
			        		console.log(data[0].materiel.placement_type)
			        		var src = data[0].materiel.region.region_name;
			        		var srcWare = src.split("-")[0];
			        		var srcRegion = src.split("-")[1];
			        		$("#src_region_id").val(data[0].materiel.region_id);
			        		$("#srcWare").val(srcWare);
			        		$("#srcRegion").val(srcRegion);
			        		$("#customer_id").val(data[0].materiel.customer_id);
			    			layer.open({
				                type: 1 				//Page层类型
				                ,area: ['500px', ''] 	//宽  高
				                ,title: '绑定目标仓库'
				                ,shade: 0.6 			//遮罩透明度
				                ,maxmin: true 			//允许全屏最小化
				                ,anim: 1 				//0-6的动画形式，-1不开启
				                ,content:$('#formDiv')
				                ,success:function(){
				                	$("#id2").val(data[0].mid);
				                }
			    			});
			        	}
					break;
		    		case 'adjust':
		    			var data = checkStatus.data;
		    			//console.log(data[0].id)
			        	if(data.length!=1){
			        		toastr.warning("请选择一条记录！");
			        	}else{
			    			layer.open({
								type: 1 		//Page层类型
								,area: ['400px', ''] //宽  高
								,title: '调整'
								,shade: 0.1 	//遮罩透明度
								,maxmin: true //允许全屏最小化
								,anim: 1 		//0-6的动画形式，-1不开启
								,content: $("#adjustDiv")
								,success:function(layero, index){
									document.getElementById("adjustform").reset();
									$("#inventId").val(data[0].id)
									form.render();
								}
			  				});
			        	}
		    		break;
				}
			});
			form.on('select(warehouseId)', function(data){
				var val = data.value;
				var customer_id = $("#customer_id").val();
				if(val==""){
					val = 0;
				}
				if(customer_id==""){
					customer_id = 0;
				}
				//通过仓库id查询库区列表
				var strWhere = 'r.warehouse_id = '+ val + ' and cw.cid = '+customer_id+' and cw.is_empty = 0 and '
				$.ajax({
					type:'post'
					,url:'${pageContext.request.contextPath }/inventoryManagement/selectWarehouseRegionListByWarehouseId.do'
					,data:{'strWhere':strWhere}
					,dataType:'json'
					,success:function(res){
						$("#region_id").find("option").not(":first").remove();
						for(var i = 0;i < res.length;i++){
							$("#region_id").append('<option value="'+res[i].id+'">'+res[i].region_name+'</option>');
						}
						form.render();
					}
				})
			}); 
			//绑定仓库
	        form.on('submit(addform2)', function (data) {
	        	$("#subform2").attr("disabled",true);
	        	$.ajax({
	        		url : '${pageContext.request.contextPath }/inventoryManagement/bindingWarehouse.do',
	       			data : $('#addform2').serialize(),
	       			type : "post",
	       			//dataType : "json",
	    			}).done(
	    				function(res) {
	    		  			if(res>0){
	    		  				toastr.success('绑定成功！');
	    	                    setTimeout(function(){
	    	                        location.reload();
	    	                    },2000);
	    		  			}else{
	    		  				toastr.error('绑定失败！');
	    		  				$("#subform2").attr("disabled",false);
	    		  			}
	    				}
	    			)
	    			return false;
	        });
		    form.on('submit(adjustform)', function (data) {
		    	$("#subadjustform").attr("disabled",true);
		    	var newMnum = $("#newMnum").val();
		    	var re = /^[0-9]*[1-9][0-9]*$/ ; 
		    	if(!re.test(newMnum) ){
		    		toastr.warning('调整数应该为正整数！')
		    		$("#subadjustform").attr("disabled",false);
		    	}else if(newMnum == ""){
		    		toastr.warning('调整数不为空！')
		    		$("#subadjustform").attr("disabled",false);
		    	}else{
		    		$.ajax({
			    		url : '${pageContext.request.contextPath }/inventoryManagement/adjust.do',
			   			data : $("#adjustform").serialize(),
			   			type : "post",
			   			//dataType : "json",
						}).done(
							function(res) {
								if(res>0){
					  				toastr.success('调整成功！')
					  				setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
					  					//关闭模态框
					  					// 父页面刷新
					  					window.location.reload();  
					  				},2000);
								}else{
									toastr.error('调整失败！')
									$("#subadjustform").attr("disabled",false);
								}
							}
						).fail(
							function(res) {
								toastr.error('调整失败！')
								$("#subadjustform").attr("disabled",false);
					  		}
						)
		    	}
				return false;
		    })
		});
		//合并单元格
		function merge(res) {
	        var data = res.data;
	        var mergeIndex = 0;//定位需要添加合并属性的行数
	        var mergeIndexAll = 0;//定位需要添加合并属性的行数
	        var mergeIndexSize = 0;//定位需要添加合并属性的行数
	        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
	        var columsName = ['customer_id'];//需要合并的列名称
	        var columsNameAll = ['materiel_name','materiel_num','devanning_code','brevity_num','packing_quantity','devanning_num','countAll','unit'];//需要合并的列名称
	        var columsNameSize = ['materiel_size','materiel_properties'];//需要合并的列名称
	        var columsIndex = [2];//需要合并的列索引值
	        var columsIndexAll = [3,4,5,6,7,8,15,18];//需要合并的列索引值
	        var columsIndexSize = [9,10];//需要合并的列索引值
	    	var allMark = 1;
	    	var sizeMark = 1;
	        for (var k = 0; k < columsNameAll.length; k++) { //这里循环所有要合并的列
	            var trArr = $("#fDiv .layui-table-body>.layui-table").find("tr");//所有行
	                for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
	                    var tdCurArr = trArr.eq(i).find("td").eq(columsIndexAll[k]);//获取当前行的当前列
	                    var tdPreArr = trArr.eq(mergeIndexAll).find("td").eq(columsIndexAll[k]);//获取相同列的第一列
	                    if(data[i].materiel.materiel_num === data[i-1].materiel.materiel_num){
	                    	allMark+=1;
	                    	tdPreArr.each(function () {//相同列的第一列增加rowspan属性
	                            $(this).attr("rowspan", allMark);
	                        });
	                        tdCurArr.each(function () {//当前行隐藏
	                            $(this).css("display", "none");
	                        });
	                    }else{
	                    	mergeIndexAll = i;
	                    	allMark=1;
	                    }
	                }
	            mergeIndexAll = 0;
	            allMark = 1;
	        } 
	        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
	            var trArr = $("#fDiv .layui-table-body>.layui-table").find("tr");//所有行
	                for (var i =   1; i < res.data.length; i++) { //这里循环表格当前的数据
	                    var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
	                    var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
	                    if (data[i].materiel[columsName[k]] === data[i-1].materiel[columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
	                        mark += 1;
	                        tdPreArr.each(function () {//相同列的第一列增加rowspan属性
	                            $(this).attr("rowspan", mark);
	                        });
	                        tdCurArr.each(function () {//当前行隐藏
	                            $(this).css("display", "none");
	                        });
	                    }else {
	                        mergeIndex = i;
	                        mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
	                    }
	                }
	            mergeIndex = 0;
	            mark = 1;
	        } 
	    }
		function mergeDetails(res) {
	        var data = res.data;
	        var mergeIndex = 0;//定位需要添加合并属性的行数
	        var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
	        var columsName = ['location_code'];//需要合并的列名称
	        var columsIndex = [2];//需要合并的列索引值
	        for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
	            var trArr = $("#details .layui-table-body>.layui-table").find("tr");//所有行
	            console.log(trArr)
	                for (var i = 1; i < res.data.length; i++) { //这里循环表格当前的数据
	                    var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
	                    var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
	                    if (data[i].zcTrayAndLocation[columsName[k]] === data[i-1].zcTrayAndLocation[columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
	                        mark += 1;
	                        tdPreArr.each(function () {//相同列的第一列增加rowspan属性
	                            $(this).attr("rowspan", mark);
	                        });
	                        tdCurArr.each(function () {//当前行隐藏
	                            $(this).css("display", "none");
	                        });
	                    }else {
	                        mergeIndex = i;
	                        mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
	                    }
	                }
	            mergeIndex = 0;
	            mark = 1;
	        }
	    }
		$(document).on('click', '#fDiv .layui-table-view .layui-table-body tr', function (event) {
	    	var trElem = $(this);
	      	var tableView = trElem.closest('.layui-table-view');
	      	tableView.find('.layui-table-body tr.table_tr_click').removeClass('table_tr_click');
	      	tableView.find('.layui-table-body tr[data-index="' + trElem.data('index') + '"]').addClass('table_tr_click');
	    });
		toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上
	</script>
</body>

</html>